package util;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Date;

@ConfigurationProperties("jwt.config")
public class JwtUtils {

    private String key;

    private long ttl;//一小时

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public long getTtl() {
        return ttl;
    }

    public void setTtl(long ttl) {
        this.ttl = ttl;
    }

    //生成jwt
    public  String createJwt(String id,String roles,String subject){
        long nowMills = System.currentTimeMillis();
        Date now = new Date(nowMills);
        JwtBuilder builder = Jwts.builder().setId(id).setIssuedAt(now).setSubject(subject)
                .signWith(SignatureAlgorithm.HS256,key).claim("roles",roles);
        if(ttl > 0){
            builder.setExpiration(new Date(nowMills + ttl));
        }
        return builder.compact();
    }


    //解析jwt
    public Claims parseJwt(String jwtStr){
        return Jwts.parser().setSigningKey(key).parseClaimsJws(jwtStr).getBody();
    }


}
